var happyReaderLink = {
    linkData:{
        main:[],
        down:[],
        other:[]
    },
    inited:false,
	hiddenSide:null,
    getData:function(contentDom){
        function getDomain(){
            var removeTag = ["com","cn","net","org","cc"],
            host = location.hostname,
            hosts = host.split(".");
            for(var idx = hosts.length - 1; idx >=0 ; idx--){
                if (!$.inArray(hosts[idx],removeTag)){
                    return hosts[idx];
                }
            }
            return host;
        }
        
        function checkDownFile(fileName){
            var downTag = ["rar", "zip", "7z", "gz", "tar", "iso", "epub", "pdf", "txt", "chm", "ppt", "pptx", "doc", "docx", "xls", "xlsx", "exe", "jar", "apk", "ipa", "m4r", "mp3", "mp4", "3gp", "avi", "rm", "rmvb", "mkv", "wma", "mpg", "pmp", "flv"],
            ext = fileName.split(".").pop();
            return $.inArray(ext, downTag)
        }
        
        function uniqueLink(links){
            var resLinksIdx = [],resLinks = [],res = [];
            for(var key in links)
                resLinks = $.mergeArray(resLinks, links[key]);
            
            //unique by url
            for(var i=0,len=resLinks.length;i<len;i++){
                var item = resLinks[i];
                if (!$.inArray(item.href,resLinksIdx)){
                    res.push(item);
                    resLinksIdx.push(item.href);
                }
            }
            return res;
        }

        var mainHost = getDomain();
        var tmpLinks = contentDom.getElementsByTagName("a");
        var mainLinks = {}, downLinks = {}, otherLinks = {};
        for(var i in tmpLinks){
            var link = tmpLinks[i];
            //filter "#","#nogo","javascript","mailto"
            if (link.href && link.href.search(/#|#nogo|javascript|mailto/i) == -1 && link.firstChild != null && link.firstChild.nodeType == 3){
			    var host = link.href.split("/")[2] , linkText = link.innerHTML.replace(/<.*?>/g,"").trim();
                if (!host || !linkText)continue;
                if (checkDownFile(linkText)){
                    if (downLinks[linkText] === undefined)
                        downLinks[linkText] = [];
                    downLinks[linkText].push({"href":link.href,"text":linkText});
                }
                else if (host.indexOf(mainHost) >= 0){
                    //get mainDomain links
                    if(mainLinks[host] === undefined)
                        mainLinks[host] = [];
                    mainLinks[host].push({"href":link.href,"text":linkText});
                }
                else{
                    if(otherLinks[host] === undefined)
                        otherLinks[host] = [];
                    otherLinks[host].push({"href":link.href,"text":link.firstChild.nodeValue});
                }
            }
        }
        this.linkData.down = uniqueLink(downLinks);
        this.linkData.main = uniqueLink(mainLinks);
        this.linkData.other = uniqueLink(otherLinks);
    },
    init:function(){
        $('#happyReaderHeaderAD').attr({onclick:function(){}}).html(_m("otherModeHeaderAD"));
		happyReader.setUserConfig("viewMode","link");
        if (this.inited)return ;
        this.inited = true;
        
        var linkCanvasID = "linkCanvas", 
            linkCanvas = $('#'+linkCanvasID);
		var html = '<button id="leftBtn" class="btn" title=""><div class="arrow leftArrow"></div></button><ul id="leftBox">';
		//left box
		html += this.buildBoxHTML('text');
		html += '</ul><ul id="rightBox">';
		//right box
		html += this.buildBoxHTML('href');
		html += '</ul><button id="rightBtn" class="btn" title=""><div class="arrow rightArrow"></div></button>';
        $('#'+linkCanvasID).css({left:0}).html(html);
		this.bindBtn();
    },
	bindBtn:function() {
		$('#leftBtn').attr({onclick:function(){
            if (happyReaderLink.hiddenSide == 'right') {
                $('#leftBox').css({width:'50%'});
                $('#rightBox').show();
                $('#rightBtn').show();
                happyReaderLink.hiddenSide = null;
            }else {
                $('#leftBtn').hide();
                $('#leftBox').hide();
                $('#rightBox').css({width:'100%'});
                happyReaderLink.hiddenSide = 'left';
            }
        }});
        $('#rightBtn').attr({onclick:function(){
            if (happyReaderLink.hiddenSide == 'left') {
                $('#rightBox').css({width:'50%'});
                $('#leftBox').show();
                $('#leftBtn').show();
                happyReaderLink.hiddenSide = null;
            }else {
                $('#rightBtn').hide();
                $('#rightBox').hide();
                $('#leftBox').css({width:'100%'});
                happyReaderLink.hiddenSide = 'right';
            }
        }});
	},
	buildBoxHTML:function(field){
		//field : text or href 
		function get(obj, color) {
			return (field == 'text') ? getText(obj.text, color) : getHref(obj.href);
		}
		function getText(text, color){
			var cls = color ? ' class="'+color+'"' : '';
			return '<li title="'+text+'"'+cls+'>'+(text||'&nbps;')+'</li>';
		}
		function getHref(href){
			return '<li title="'+href+'"><a href="'+href+'">'+(href||'&nbsp;')+'</a></li>';
		}
		var html = "";
		//add download links
		if (this.linkData.down.length > 0) {
            this.linkData.down.forEach(function(item, dix){
                html += get(item, 'downlink');
            });
			html += '<hr/>';
        }
		//add mainDomain links
		if (this.linkData.main.length > 0) {
            this.linkData.main.forEach(function(item,idx){
				html += get(item);
            });
			html += '<hr/>';
        }
		//add otherDomain links
        if (this.linkData.other) {
			this.linkData.other.forEach(function(item, idx){
				html += get(item);
			});
		}
		return html;
	},
	checkModeValid:function(){
        return this.linkData.main.length > 0;
    }
};